<?php
namespace common\models;

use Yii;
use yii\base\Model;
use yii\base\InvalidParamException;
use common\models\User;

class ChangePasswordForm extends Model
{

    public $oldpassword;
    public $newpassword1;
    public $newpassword2;

    private $_user;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['oldpassword', 'newpassword1', 'newpassword2'], 'required'],
            [['oldpassword', 'newpassword1', 'newpassword2'], 'string', 'min' => 6],
            ['oldpassword', 'validatePassword'],
            ['newpassword2', 'compare', 'compareAttribute' => 'newpassword1'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'oldpassword' => Yii::t('common', 'old_{value}_password', ['value' => Yii::t('common', 'login')]),
            'newpassword1' => Yii::t('common', 'new_{value}_password', ['value' => Yii::t('common', 'login')]),
            'newpassword2' => Yii::t('common', 'sure_{value}_password', ['value' => Yii::t('common', 'login')]),
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            if (!$user->validatePassword($this->oldpassword)) {
                $this->addError($attribute, Yii::t('common', 'incorrect_oldpassword'));
            }
        }
    }

    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    protected function getUser()
    {
        if ($this->_user === null) {
            $this->_user = User::findIdentity(Yii::$app->user->id);
        }

        return $this->_user;
    }

    /**
     * 修改登录密码
     * @return bool
     */
    public function changePassword(){
        $user = $this->getUser();
        if($user->validatePassword($this->oldpassword)){
            if($this->newpassword1 == $this->newpassword2){
                $user->setPassword($this->newpassword1);
                $user->removePasswordResetToken();
                if($user->save()){
                    return true;
                }else{
                    return false;
                }
            }else{
                Yii::$app->session->setFlash('error',Yii::t('common', 'newpassword_neq'));
                return false;
            }
        }else{
            Yii::$app->session->setFlash('error',Yii::t('common', 'incorrect_old_{value}', ['value' => Yii::t('common', 'login')]));
            return false;
        }
    }


}